package com.loan.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.loan.service.FileService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Resource
    RedisTemplate redisTemplate;

    String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
    String KEY_ID = "LTAI5t9zUWC9nJKrEqaGh66Q";
    String KEY_SECRET = "igYHaqxeMFCi0qlk48isnuqe1sIkK7";
    String BUCKET_NAME = "vue-bank-20240927";

    @Override
    public String upload(InputStream inputStream, String module, String fileName) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, KEY_ID, KEY_SECRET);

        // 判断BUCKET_NAME是否存在
        if(!ossClient.doesBucketExist(BUCKET_NAME)){
            ossClient.createBucket(BUCKET_NAME);
            ossClient.setBucketAcl(BUCKET_NAME, CannedAccessControlList.PublicRead);
        }

        // 上传文件流。
        // 文件目录结构 "用户名 + 文件名"
        //构建路径
        String userName = String.valueOf(redisTemplate.opsForValue().get("userName"));
        String Folder = ("/"+module+"/");
        //文件名生成
        fileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        String key = userName + Folder + fileName;
        System.out.println("key:"+key);
        ossClient.putObject(BUCKET_NAME, key, inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

        //文件的url地址
        //https:// bucketname   .  endpoint / + key
        String url = "https://" + BUCKET_NAME + "." + ENDPOINT + "/" + key;
        System.out.println("文件路径url:"+url);
        return url;
    }

    @Override
    public void removeFile(String url) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, KEY_ID, KEY_SECRET);

        // https://oss-cn-beijing.aliyuncs.com/
        String host = "https://" + BUCKET_NAME + "." + ENDPOINT + "/";
        String objectName = url.substring(host.length());

        // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
        ossClient.deleteObject(BUCKET_NAME, objectName);

        // 关闭OSSClient。
        ossClient.shutdown();
    }
}
